package com.bzyd.derby.plugin;

import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * 分页请求信息
 */
public class Page {

    /**
     * 分页页码
     */
    private int pageIndex;

    /**
     * 单页数据量
     */
    private int pageSize;

    /**
     * 总条数
     */
    private int count;

    /**
     * 排序字段
     */
    private String sortBy;

    /**
     * 排序方式：desc，asc
     */
    private String rank;

    public Page() {
        this(1, 10, null, null);
    }

    public Page(int pageIndex, int pageSize) {
        this(pageIndex, pageSize, null, null);
    }

    public Page(int pageIndex, int pageSize, String sortBy, String rank) {
        if (pageIndex <= 0) {
            throw new IllegalArgumentException("分页页码必须大于0");
        }
        if (pageSize <= 0) {
            throw new IllegalArgumentException("单页数据量必须大于0");
        }
        if (StringUtils.isNotEmpty(rank)) {
            rank = rank.toLowerCase().trim();
            if (!"desc".equals(rank) && !"asc".equals(rank)) {
                throw new IllegalArgumentException("排序方式参数不正确");
            }
        }

        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
        this.sortBy = sortBy;
        this.rank = rank;
    }

    public int getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        if (pageIndex <= 0) {
            throw new IllegalArgumentException("分页页码必须大于0");
        }
        this.pageIndex = pageIndex;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        if (pageSize <= 0) {
            throw new IllegalArgumentException("单页数据量必须大于0");
        }
        this.pageSize = pageSize;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getSortBy() {
        return sortBy;
    }

    public void setSortBy(String sortBy) {
        this.sortBy = sortBy;
    }

    public String getRank() {
        return rank;
    }

    public void setRank(String rank) {
        if (StringUtils.isNotEmpty(rank)) {
            rank = rank.toLowerCase().trim();
            if (!"desc".equals(rank) && !"asc".equals(rank)) {
                throw new IllegalArgumentException("排序方式参数不正确");
            }
        }
        this.rank = rank;
    }

    public <T> PageInfo<T> getPageInfo(List<T> result) {
        PageInfo<T> pageInfo = new PageInfo<>();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotalNum(count);
        pageInfo.setTotalPage(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        pageInfo.setResult(result);
        return pageInfo;
    }
}
